<?php

namespace App\Api\Controllers;

use App\Jobs\Elesticsearch;
use App\Jobs\LogQueue;
use App\Jobs\PushQueue;
use App\Models\FailFriend;
use App\Models\FriendModel;
use App\Models\FriendUser;
use App\Models\JpushMobile;
use App\Models\MobileMark;
use App\Models\UserDynamicList;
use App\Services\ActivityService;
use App\Services\Behavior;
use App\Services\Filter;
use App\Services\MediaService;
use App\Services\Pusher;
use App\Services\UploadService;
use App\Services\UserService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\MediaClass;
use App\Models\Media;
use App\Models\MediaStar;
use App\Models\Friend;
use App\Models\MediaHistory;
use App\Exceptions\ApiException;
use App\Models\User;
use App\Models\UserTicket;
use App\Models\MediaComment;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Yankewei\LaravelSensitive\Facades\Sensitive;
use DateTime;
use App\Services\Log;
use App\Services\Sts;
use App\Models\ActivityConfig;
use App\Enum\ActivityEnum;

//测试类
class IndexController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        // 获取用户基本信息
        $this->getUserInfo(false);
    }

    //首页
    public function index()
    {
        return json_success('ok', [], 10000);
    }

    /**
     * 获取网页上传OSS签名
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function getWapUploadToken(Request $request)
    {
        $type = IT('type',true,'未知上传文件类型', 10031);

        if(!in_array($type, config('params.oss_file_type')))
            return json_error('未知上传文件类型', [], 10031);

        $userTicket = UserTicket::where([
            ['status','=',1],
            ['ticket','=', $request->input('ticket')],
            ['client_source','=',$request->input('ClientSource')]
        ])->first();

        if ($userTicket && $userTicket->_user()->first()) {
            $uid = $userTicket->uid;
        } else {
            $_SERVER['message_code'] = 10032;
            throw new ApiException('参数有误', 0);
        }

        $id = env('WEB_ACCESS_ID');
        $key = env('WEB_ACCESS_KEY');
        $host = 'http://'.env('WEB_BUCKET_NAME').'.'.env('WEB_ENDPOINT');

        $now = time();
        $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);

        $dir = $type.'/'.substr(md5($uid), 0, 4) . '/' . date('Ym') . '/';

        //最大文件大小.用户可以自己设置
        $condition = ['content-length-range', 0, 10240000];
        $conditions[] = $condition;

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = ['starts-with', '$key', $dir];
        $conditions[] = $start;

        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);

        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['filename'] = date('Ymd') . md5(uniqid()) ;
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;

        return json_success('ok', $response, 10000);
    }

    private function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }

    /**
     * 获取OSS上传文件token
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function getUploadToken(Request $request)
    {
        $mobile_unique_code = IT('mobile_unique_code', true, '参数有误', 10032);
        $ticket = IT('ticket');

        $uid = 0;
        $ticket_rows = UserTicket::where([['ticket', '=', $ticket]])->first();
        if(!empty($ticket_rows))
            $uid = $ticket_rows->uid;

        // 返回app 的有效期
        $expires_in = 3000;
        if(empty(Redis::get('oss_token:'.$mobile_unique_code))){
            $expires = 3600;
            $data = Sts::getData($expires);
            Redis::setex('oss_token:'.$mobile_unique_code, $expires_in, json_encode(['start_time'=>time(), 'data'=>$data]));
            $securityToken = $data['SecurityToken'];
        }else{
            $cacheOssToken = json_decode(Redis::get('oss_token:'.$mobile_unique_code), true);
            $data = $cacheOssToken['data'];
            $expires_in = $expires_in-(time()-$cacheOssToken['start_time']);
            $securityToken = $cacheOssToken['data']['SecurityToken'];
        }
        if($expires_in <= 0 )
            return json_error('token 失效', [], 10033);
        if(empty($securityToken))
            return json_error('系统错误',[], 10034);

        $data['callbackUrl'] = route('callback');
        $data['callbackBody'] = 'filename=${object}&size=${size}&bucket=${bucket}&etag=${etag}&mimeType=${mimeType}&system=${x:system}&ticket=${x:ticket}&path=${x:path}&media_id=${x:media_id}&uid=${x:uid}';

        // 构造目录
        $temp_arr = [];
        foreach (config('params.oss_file_type') as $oss_path){
            $extend_path = '';
            if(in_array($oss_path, ['idcard', 'member_avatar']))
                $extend_path = 'images/';
            $temp_arr[$oss_path] = substr(md5($mobile_unique_code), 0, 4).'/'.$extend_path. $oss_path . '/' . date('Ymd') . '/' . date('Ymd') . md5(uniqid().$oss_path);
        }

        $data['xpath'] = $temp_arr;
        $data['expires_in'] = $expires_in;
        $data['oss_cdn'] = [
            'cdn_enable'=> (config('basic.oss_cdn.oss_cdn_enable') == true) ? 1 : 0,
            'cdn_url'=>config('basic.oss_cdn.oss_cdn_url'),
            'cdn_key'=>config('basic.oss_cdn.oss_cdn_key'),
        ];

        // 更新登陆时间
        $userTicket = UserTicket::where([['ticket', '=', $ticket]])->first();
        if(!empty($userTicket))
            DB::update('UPDATE `users` SET `updated_at`=? WHERE `id`=? ', [time2date(), $userTicket->uid]);

        return json_success('ok', $data, 10000);
    }

    /**
     * 上传视频回调
     * @return array
     * @throws ApiException
     */
    public function callback()
    {
        $data = file_get_contents('php://input');
        parse_str($data, $params);
        extract($params); //视频参数

        // 调试
        Redis::setex("test:index_callback:".time(), 60, json_encode($data));

        if (!isset($path) || !isset($ticket) || !isset($media_id)){
            $_SERVER['message_code'] = 10032;
            throw new ApiException('参数错误');
        }

        if(!isset($uid) || empty($uid)){
            // 检查ticket是否有效
            $userTicket = UserTicket::where([['ticket', '=', $ticket], ['status', '=', 1]])->first();
            if ($userTicket && $userTicket->_user()->first()) {
                $uid = $userTicket->uid;
            }else {
                $_SERVER['message_code'] = 10032;
                throw new ApiException('参数有误');
            }
        }

        $media = Media::find($media_id);
        if (!$media || $media->uid != $uid) {
            $_SERVER['message_code'] = 10032;
            throw new ApiException('参数有误');
        }

        $media->media = 'http://' . env('BUCKET_NAME') . '.' . env('STS_ENDPOINT') . '/' . $path;
        $media->status = 1;
        $media->save();

        // 初始化点赞统计信息
        if($media->is_participate_activity == 1)
            MediaService::init_media_like_static($uid);

        if($media->is_private != '1'){
            $temp_arr = [];
            // 队列   --添加搜索索引
            $temp_arr['mid'] = $media_id;
            $temp_arr['title'] = $media->title;
            $temp_arr['description'] = $media->description;
            $temp_arr['cover'] = $media->cover;
            dispatch((new Elesticsearch(['type'=>'2', 'action'=>'add', 'data'=>$temp_arr]))->onQueue('eleasticsearch'));
        }

        // 关注推送
        if ($media->is_private == '0') {
            $attentionUserList = FriendUser::where([['friend_id', '=', $media->uid], ['status', '=', '1']])->with('user')->get();
            if ($attentionUserList) {
                // 遍历推送
                foreach ($attentionUserList as $value) {
                    if (!empty($value->user->registration_id)) {
                        $registration_id = $value->user->registration_id;

                        /*Pusher::message($registration_id, '您关注的用户发布了新视频', ['type' => 0]);
                        Pusher::alert($registration_id, '您关注的用户发布了新视频');*/

                        $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $registration_id]]);
                        // 消息推送
                        if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){

                            ////////////////////////////////////////////////////////////////////////////////////////////////
                            $data = [];
                            $push_channel_key = 'jpush';
                            if($getPushChannel['push_channel_id'] == 2){
                                $push_channel_key = 'hpush';
                            }else if($getPushChannel['push_channel_id'] == 3){
                                $push_channel_key = 'xmpush';
                            }

                            // 标题  --app 通过notify id 0处理业务 --透传
                            $data['channel_id'] = $getPushChannel['push_channel_id'];
                            $data['title'] = trans('notice.10259');//'您关注的用户发布了新视频'; // 登录标题
                            $data['content'] = trans('notice.10259');//'您关注的用户发布了新视频';// 内容
                            $data['description'] = trans('notice.10259');//'您关注的用户发布了新视频'; // 描述
                            $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                            $data['notify_id'] = 0;     // 通知id   --app 处理业务标识
                            $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                            $data['mobile_list'] = $getPushChannel['registration_id'];
                            // $data['mobile_unique_code'] = IT('mobile_unique_code');
                            dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                            // 保留原始功能
                            if($push_channel_key == 'jpush'){
                                // 发通知提示用户   --通知
                                unset($data['msg_type']);
                                $data['msg_type'] = config('push')[$push_channel_key]['type']['notify'];  // 消息类型：1通知 0透传
                                dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                            }
                            ////////////////////////////////////////////////////////////////////////////////////////////////
                        }
                    }
                }
            }
        }

        // 亲友圈推送
        if ($media->is_private == 0 || $media->is_private == 2) {

            $friendList = FriendModel::where([['friend_uid', '=', $media->uid], ['status', '=', '1']])->with('user')->get();
            if(!empty($friendList)){
                foreach ($friendList as $value){
                    if(!empty($value->user->registration_id)){
                        $registration_id = $value->user->registration_id;
                        if ($registration_id) {

                            $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $registration_id]]);
                            // 消息推送
                            if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){

                                ////////////////////////////////////////////////////////////////////////////////////////////////
                                $data = [];
                                $push_channel_key = 'jpush';
                                if($getPushChannel['push_channel_id'] == 2){
                                    $push_channel_key = 'hpush';
                                }else if($getPushChannel['push_channel_id'] == 3){
                                    $push_channel_key = 'xmpush';
                                }

                                // 标题  --app 通过notify id 0处理业务 --透传
                                $data['channel_id'] = $getPushChannel['push_channel_id'];
                                $data['title'] = trans('notice.10260');//'亲友发布视频'; // 登录标题
                                $data['content'] = trans('notice.10260');//'您的亲友圈好友发布了新视频';// 内容
                                $data['description'] = trans('notice.10260');//'您的亲友圈好友发布了新视频'; // 描述
                                $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                                $data['notify_id'] = 1;     // 通知id   --app 处理业务标识
                                $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                                $data['mobile_list'] = $getPushChannel['registration_id'];
                                // $data['mobile_unique_code'] = IT('mobile_unique_code');
                                dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));

                                // 保留原始功能
                                if($push_channel_key == 'jpush'){
                                    // 发通知提示用户   --通知
                                    unset($data['msg_type']);
                                    $data['msg_type'] = config('push')[$push_channel_key]['type']['notify'];  // 消息类型：1通知 0透传
                                    dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                                }
                                ////////////////////////////////////////////////////////////////////////////////////////////////
                            }
                        }
                    }
                }
            }
        }

        return json_success('ok', ['media' => $media], 10000);
    }

    public function category(Request $request)
    {
        $data = MediaClass::where('status',1)->get(['id','name']);
        $data->prepend(['id'=>0,'name'=>'全部']);
        return json_success('ok',$data, 10000);
    }

    /*
     * 视频列表1.5.*
     * */
    public function categoryList(Request $request)
    {
        $media_list = MediaService::getIndexMedia($request);

        // 埋点检测用户在线   一天一条记录
        UserService::check_online();
        if(empty($media_list))
            return json_success('暂无数据', [], 10157);
        return json_success('ok',$media_list, 10000);

        /*
         * --待作废
         * 2.2.1 之前
         * $type = $request->input('type');
        $page = intval($request->input('page'))?:1;
        $page = $page - 1;
        $pageSize = config('admin.pageSize');

        $fields = ['id','title','description','media','comments','star','like','is_like','uid','created_at','address','location','cover','video_length','share'];
        $where = [ ['status','=',1],['is_delete','=',0], ['is_private', 0] ];

        // 获取用户token
        $view_user_ticket = UserTicket::where([['ticket',$request->input('ticket')],['client_source',$request->input('ClientSource')], ['status',1]])->first();

        // 获取视频列表
        $media_list = $this->getMediaListByType($type, $where, $fields, $page, $pageSize, $view_user_ticket);
        if(isset($media_list['status']) && $media_list['status'] == 'error')
            return json_error('查询失败', [], 10035);

        // 有何用途？？？？？？？？？？？？
        if ($ticket = $request->input('ticket')) {
            $uid = D('user_tickets')->where('ticket', $ticket)->value('uid');
            $notice = D('users')->where('id', $uid)->value('notice');
        }

        return json_success('ok',$media_list, 10000);*/
    }

    /*
     * 2.2.1 之前功能-- 待作废
     * */
    private function getMediaListByType($type, $where, $fields, $page, $pageSize, $view_user_ticket)
    {
        $is_login = $view_user_ticket && $view_user_ticket->_user()->first();
        // 若用户登录，查询发布的最新一条的视频
        if ($is_login && $page === 0)
            $user_latest_media = MediaService::userNewMedia($view_user_ticket);

        // 如果是第一页的最新和最热，要少查询一条
        if (isset($user_latest_media) && $user_latest_media && in_array($type, ['hot', 'recommend']))
            $pageSize = $pageSize - 1;

        switch ($type) {
            /*// 最新
            case 'new':
                $media_list = Media::where($where)->skip($page*$pageSize)->take($pageSize)->orderBy('created_at','desc')->get($fields);
                break;
            // 热门
            case 'hot':
                $media_list = Media::where($where)->skip($page*$pageSize)->take($pageSize)->orderBy('star','desc')->orderBy('pv','desc')->get($fields);
                break;*/
            // 关注
            case 'follow':
                $media_list = array();
                if ($is_login) {
                    $offset = $page * $pageSize;

                    $feild = 'm.`id`, m.`title`, m.`description`, m.`media`,m.`comments`,m.`star`,m.`like`,m.`is_like`,m.`uid`,m.`created_at`,m.`address`, m.`location`,m.`cover`,m.`video_length`,m.`share` ,u.avatar,u.name';
                    $sql = "select {$feild} from media as m "
                        ." left join users as u"
                        ." on m.uid=u.id"
                        ." where m.status=1 and is_delete=0 and m.is_private=0 "
                        ." and (m.uid in (select friend_id from friend_user where uid={$view_user_ticket->uid} and status=1) ) "
                        ." ORDER BY m.`id` DESC LIMIT {$offset},{$pageSize}";

                    $media_list = DB::select($sql);
                }
                break;
            // 亲友圈
            case 'friend':
                $media_list = array();
                if ($is_login) {
                    $offset = $page * $pageSize;

                    $feild = 'm.`id`, m.`title`,m.`description`, m.`media`,m.`comments`,m.`star`,m.`like`,m.`is_like`,m.`uid`,m.`created_at`,m.`address`,m.`location`,m.`cover`,m.`video_length`,m.`share` ,u.avatar,u.name';
                    $sql = "select {$feild} from media as m "
                        ." left join users as u"
                        ." on m.uid=u.id"
                        ." where m.status=1 and is_delete=0 and m.is_private!=1 "
                        ." and (m.uid in (select uid from friend where friend_uid={$view_user_ticket->uid} and status=1) ) " // m.uid in (select friend_uid as uid from friend where uid={$view_user_ticket->uid} and status=1) or
                        ." ORDER BY m.`id` DESC LIMIT {$offset},{$pageSize}";

                    $media_list = DB::select($sql);
                }
                break;
            // 推荐
            case 'recommend':

                $mobile_unique_code = IT('mobile_unique_code');
                $mobileMarkRows = MobileMark::getRowsArray([['mobile_unique_code', '=', $mobile_unique_code]]);

                $c = DB::connection('mysql2');

                $media_ids = '';
                if($is_login){
                    $media_ids = $c->table('recommend_list')->where('uid', $view_user_ticket->uid)->value('vids');
                }else{

                    // 通过设备
                    if(!empty($mobileMarkRows)){
                        $media_ids = $c->table('non_login_list')->where([['did', '=', $mobileMarkRows['id']]])->value('vids');
                    }
                }
                // 取默认推荐
                if(empty($media_ids)){
                    $media_ids = $c->table('recommend_list')->where([['uid', '=', '0']])->value('vids');
                }

                $media_list = [];
                if(!empty($media_ids)){
                    $media_ids_arr = explode(',', $media_ids);
                    $_media_ids = array_slice($media_ids_arr, $page * $pageSize, $pageSize);

                    if(!empty($_media_ids)){
                        $feild = 'm.`id`, m.`title`,m.`description`, m.`media`,m.`comments`,m.`star`,m.`like`,m.`is_like`,m.`uid`,m.`created_at`,m.`address`,m.`location`,m.`cover`,m.`video_length`,m.`share` ,u.avatar,u.name';
                        $sql = "select ".$feild." from media as m left join users as u on m.uid=u.id where m.status=1 and m.is_delete=0 and m.is_private=0
                        and m.id in (".implode(',', $_media_ids).") order by field (m.id,".implode(',', $_media_ids).")"; //

                        $media_list = DB::select($sql);
                    }
                }

                if(!empty($_media_ids) && !empty($_media_ids[0])){
                    $did = (isset($mobileMarkRows['id']) && intval($mobileMarkRows['id']) > 0 ) ? $mobileMarkRows['id'] : 0;

                    // 存储list 列表
                    Redis::rPush('algorithm_log', json_encode(['type'=>'filtr_recommend', 'create_time'=>time(), 'data'=>['uid'=>(!empty($view_user_ticket) ? $view_user_ticket->uid : 0), 'did'=>$did, 'media_ids'=>implode(',', $_media_ids)]]));
                    // 队列  --写入行为记录 --可删除
                    // dispatch((new LogQueue(['type'=>'filtr_recommend', 'data'=>['uid'=>(!empty($view_user_ticket) ? $view_user_ticket->uid : 0), 'did'=>$did, 'media_ids'=>implode(',', $_media_ids)]]))->onQueue('log_queue'));
                }
                break;
            default:
                $media_list = array();
                break;
        }

        $handleDataOfMediaList = MediaService::handleDataOfMediaList($media_list, $view_user_ticket);
        if($handleDataOfMediaList['status'] == 'error')
            return $handleDataOfMediaList;

        $temp_media_arr = [];
        // 存在个人发布最后一条视频
        if(!empty($user_latest_media) && in_array($type, ['hot', 'recommend']))
            $temp_media_arr[] = $user_latest_media->toArray();
        else
            if(!empty($media_list))
                $temp_media_arr = $media_list;

        if (!empty($media_list) && !is_array($media_list))
            $media_list = $media_list->toArray();

        // 若查询的视频包含用户最新的视频，去掉，重新查询一条
        if (isset($user_latest_media) && $user_latest_media && in_array($type, ['hot', 'recommend']) && !empty($media_list)) {

            foreach ($media_list as $k => &$item) {
                if(is_array($item))
                    $media_id = $item['id'];
                else
                    $media_id = $item->id;
                if ($media_id === $user_latest_media->id) {
                    continue;
                    unset($media_list[$k]);
                }
                $temp_media_arr[] = $item;
            }
        }

        return $temp_media_arr;
    }

    /**
     * 获取资讯详情信息
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function mediaDetail(Request $request)
    {
        $id = $request->input('id');
        $ticket = $request->input('ticket');
        $ClientSource = $request->input('ClientSource');
        $page = intval($request->input('page'))?:1;
        $page = $page - 1;
        $pageSize = config('admin.pageSize');
        $media = Media::where('id', $id)->first();
        if (!$media){
            $_SERVER['message_code'] = 10036;
            throw new ApiException('未找到相应内容');
        }

        if(isset($ticket)){
            MediaHistory::addMediaHistory($id, $ticket);
            $data = $this->getDataOfMediaDetail($media, $ticket,$ClientSource, $page, $pageSize);
        }else{
            $data = $this->getDataOfMediaDetail($media,null, $ClientSource, $page, $pageSize);
        }

        return json_success('ok',$data,10000);
    }

    /**
     * 分享详情
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function sharing_details(Request $request)
    {
        $id = IT('id',true,'请填写视频ID',10037);
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.location', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover', 'media.video_length', 'users.name as uname', 'users.avatar', 'media.is_participate_activity', 'media.description'];
        $media = Media::where('media.id', $id)->join('users', 'users.id', '=', 'media.uid')->first($fields);
        if(!$media){
            EE('没有该视频',0, 10038);
        }
        $media['media'] = getSignUrl($media['media']);
        $media['cover'] = getSignUrl($media['cover']);
        $media['avatar'] = getSignUrl($media['avatar']);
        $media['title'] = $media->is_participate_activity == 1 ? $media['title'].'【点击这里，带我一起冲击万元大奖】' : $media['title'];
        $media['description'] = $media->is_participate_activity == 1 ? '我的影片正在参加微电影人气PK赛，欢迎各路大神围观。帮我点赞助力，共同创作一起拿万元大奖，关注、点赞、转发，大家一起发发发。' : $media['description'];
        return json_success('ok', $media, 10000);
    }

    /**
     * 获取媒体详细信息的数据
     * @param $media 媒体表的对象句柄
     * @param $page 页数
     * @param $pageSize
     * @return array
     */
    private function getDataOfMediaDetail($media, $ticket,$ClientSource, $page, $pageSize)
    {
        $data = [];
        $data['comments_total'] = $media->comments;
        $data['title'] = $media->title;
        $data['avatar'] = $media->_user->avatar;
        $data['username'] = $media->_user->name;
        $data['cover'] = $media->cover;
        $data['uid'] = $media->_user->id;
        $data['created_at'] = $media->created_at->format('Y-m-d H:i:s');
        $data['content'] = $media->content;
        $data['type'] = $media->type;
        $data['media'] = $media->media;
        $data['comments'] = $media->_comments()->where([ ['parent_id','=',0],['is_delete','=',0] ])->skip($page*$pageSize)->take($pageSize)->orderBy('created_at','desc')->get(['content','created_at','uid','id']);
        $data['is_author_star'] = 1;
        $data['address'] = $media->location;
        $data['video_length'] = $media->video_length;
        $data['cover'] = getSignUrl($data['cover']);
        $data['media'] = getSignUrl($data['media']);
        $data['avatar'] = getSignUrl($data['avatar']);

        foreach ($data['comments']  as $k=>&$v) {
            $v->is_allow_delete = 0;  //初始化
        }
        $user_ticket = UserTicket::where([ ['status','=',1],['ticket','=',$ticket] ])->first();
        $star = 0 ; //关注状态：0未关注，1已关注
        if ($user_ticket)
        {
            $user = $user_ticket->_user()->first();
            if ($user)
            {
                if ( MediaStar::where([ ['uid','=',$user->id],['media_id','=',$media->id],['status','=',1] ])->first() ){
                    $data['is_media_star'] = 1; //已收藏该资讯
                }else {
                    $data['is_media_star'] = 0;      //未收藏该资讯
                }

                foreach ($data['comments']  as $k=>&$v) {
                    if ($user && $v->uid == $user->id){      //如果是要查看其他用户主页,且该用户已登录,但查看的是自己的信息
                        $v->is_allow_delete = 1;  //自己查看自己的允许删除
                    }else {
                        $v->is_allow_delete = 0;  //查看不是自己的不允许删除
                    }
                }
                $star = D('friend_user')->where([['uid', $user->id], ['friend_id', $media->uid], ['status', 1]])->first() ? 1 : 0 ;
                if ($user->id == $media->uid) {
                    $data['is_author_star'] = -1;
                    $star = -1;
                }
            }
        }
        $data['star'] = $star;
        $media->pv = $media->pv+1;
        $media->save();
        return $data;
    }
    //详情页一级评论
    public function mediaComments(Request $request)
    {
        $id =  $request->input('id');
        $page = intval($request->input('page'))?:1;
        $page = $page - 1;
        $pageSize = config('admin.pageSize');

        $offset = $page * $pageSize;
        $data = DB::select('SELECT mc.`content`,mc.`created_at`,mc.`uid`,mc.`id`,u.`avatar`,u.`name`,
                          (SELECT COUNT(1) FROM `media_comment` WHERE `media_comment`.`parent_id`=mc.`id` AND `media_comment`.`status`=1 AND `media_comment`.`is_delete`=0) AS replay_count
                           FROM `media_comment` AS mc INNER JOIN `users` AS u ON mc.`uid`=u.`id` 
                           WHERE mc.`media_id`=? AND mc.`status`=1 AND mc.`is_delete`=0 AND mc.`parent_id`=0 AND u.`status`=1 
                           ORDER BY mc.`id` DESC LIMIT ?,?', [$id, $offset, $pageSize]);

        foreach ($data as &$reply)
        {
            $reply->avatar = getSignUrl($reply->avatar);
        }
        return json_success('ok',$data, 10000);
    }

    /**
     * 获取评论详细信息（包含回复）
     *
     * @param Request $request
     * @return void
     * @date
     * @version v1.0
     */
    public function mediaCommentDetail(Request $request)
    {
        $page = intval($request->input('page'))?:1;
        $page = $page - 1;
        $pageSize = config('admin.pageSize');
        $id =  $request->input('id');
        $comment = MediaComment::find($id);
        $myUser = User::getUserInfo($request->input('ticket'));
        if (!$comment)
        {
            $_SERVER['message_code'] = 10039;
            throw new ApiException('未找到该评论');
        }
        else if ($comment->is_delete)
        {
            $_SERVER['message_code'] = 10040;
            throw new ApiException('该评论已被删除');
        }
        $comment_user_info = $comment->_user()->first(['avatar','name']);

        $comment_user_info->avatar = getSignUrl($comment_user_info->avatar);
        list( $data['avatar'], $data['username'] ) = [ $comment_user_info->avatar , $comment_user_info->name ];
        $data = $comment->_replys()->where([ ['is_delete','=',0] ])->skip($page*$pageSize)->take($pageSize)->get(['content','created_at','uid','id']);

        foreach ($data as $k => &$reply)
        {
            $reply_user_info = $reply->_user()->first(['avatar','name']);
            if (!$reply_user_info) {
                unset($data[$k]);
                continue;
            }
            list($reply['avatar'],$reply['username']) = [ getSignUrl($reply_user_info->avatar) , $reply_user_info->name ];
            if ($myUser && $reply->uid == $myUser->id){      //如果是要查看其他用户主页,且该用户已登录,但查看的是自己的信息
                $reply->is_allow_delete = 1;  //自己查看自己的允许删除
            }else {
                $reply->is_allow_delete = 0;  //查看不是自己的不允许删除
            }

        }
        return json_success('ok',$data, 10000);
    }

    /**
     * 发布评论
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function addMediaComment(Request $request)
    {
        $id = IT('id', true, '请选择视频', 10041);
        $content = IT('content', true, '请输入评论内容', 10042);

        $user = User::getUserInfo($request->input('ticket'));
        $comment = new MediaComment;
        $comment->uid = $user->id;
        $comment->media_id =  $id;
        //内容关键词过滤
        $comment->parent_id = 0;
        $interference = ['&', '*'];
        $filename = config_path().'/sensitiveword.txt'; //每个敏感词独占一行
        Sensitive::interference($interference); //添加干扰因子
        Sensitive::addwords($filename); //需要过滤的敏感词
        $filter_content = Sensitive::filter($content);
//        if ( strcmp($filter_content,$content)!=0 && config('basic.sensitive_data_filter')=='prevent' ) { //存在敏感词
//            throw new ApiException('内容包含敏感词',0);
//        }
        $filter_content = Filter::init($filter_content);

        $media = Media::find($id);
        if (!$media){
            $_SERVER['message_code'] = 10043;
            throw new ApiException('您想要评论的资讯不存在，无法评论',0);
        }elseif ($media->is_delete) {
            $_SERVER['message_code'] = 10044;
            throw new ApiException('您想要评论的资讯已被删除，无法评论',0);
        }
        $media->comments = $media->comments+1;
        $media->save();
        $comment->content = $filter_content;
        $comment->save();

        if($comment){
            // 推送
            $_user = D('users')->find($media->uid);
            if ($_user && $_user->registration_id) {

                /*Pusher::message($_user->registration_id, '其他用户评论了您发布的视频', ['type' => 2]);*/

                $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $_user->registration_id]]);
                // 消息推送
                if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){

                    ////////////////////////////////////////////////////////////////////////////////////////////////
                    // 标题  --app 通过notify id 0处理业务 --透传
                    $data = [];
                    $push_channel_key = 'jpush';
                    if($getPushChannel['push_channel_id'] == 2){
                        $push_channel_key = 'hpush';
                    }else if($getPushChannel['push_channel_id'] == 3){
                        $push_channel_key = 'xmpush';
                    }

                    $data['channel_id'] = $getPushChannel['push_channel_id'];
                    $data['title'] = '亲友发布视频'; // 登录标题
                    $data['content'] = '您的亲友圈好友发布了新视频';// 内容
                    $data['description'] = '您的亲友圈好友发布了新视频'; // 描述
                    $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                    $data['notify_id'] = 2;     // 通知id   --app 处理业务标识
                    $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                    $data['mobile_list'] = $getPushChannel['registration_id'];
                    $data['mobile_unique_code'] = IT('mobile_unique_code');
                    dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                    ////////////////////////////////////////////////////////////////////////////////////////////////
                }
            }

            $data = [
                'uid' =>  $user->id,
                'username' => $user->name,
                'id'=> $comment->id,
                'avatar' => $user->avatar,
                'content' =>$comment->content,
                'replay_count' =>MediaComment::where('parent_id','=',$media->id)->count(),
                'created_at' =>time2date(),
            ];
            return json_success('ok',$data, 10000);
        }
    }


    /**
     * 对评论进行回复
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function addMediaReply(Request $request)
    {
        Log::info(__FILE__, 'addMediaReply', $_GET,  IT('id'));
        $id = IT('id', true, '请选择视频', 10044);
        $content = IT('content', true, '请输入回复内容', 10045);
        $host = 'http://'.env('WEB_BUCKET_NAME').'.'.env('WEB_ENDPOINT');
        $user = User::getUserInfo($request->ticket);
        $comment = new MediaComment;
        $comment->uid = $user->id;
        //内容关键词过滤
        $comment->parent_id = 0;
        $interference = ['&', '*'];
        $filename = config_path().'/sensitiveword.txt'; //每个敏感词独占一行
        Sensitive::interference($interference); //添加干扰因子
        Sensitive::addwords($filename); //需要过滤的敏感词

        $filter_content = Sensitive::filter($content);
//        if ( strcmp($filter_content,$content)!=0 && config('basic.sensitive_data_filter')=='prevent' ) { //存在敏感词
//            throw new ApiException('内容包含敏感词',0);
//        }
        $filter_content = Filter::init($filter_content);
        $mediacomment = MediaComment::find($id);
        if (!$mediacomment){
            $_SERVER['message_code'] = 10046;
            throw new ApiException('您想要回复的评论不存在，无法回复',0);
        }elseif ($mediacomment->is_delete) {
            $_SERVER['message_code'] = 10047;
            throw new ApiException('您想要回复的评论已被删除，无法回复',0);
        }
        $media = $mediacomment->_media()->first();
        if (!$media) {
            $_SERVER['message_code'] = 10046;
            throw new ApiException('您想要回复的资讯不存在，无法回复',0);
        }else if($media->is_delete) {
            $_SERVER['message_code'] = 10048;
            throw new ApiException('您想要回复的资讯已被删除，无法回复',0);
        }
        $media->comments = $media->comments+1;
        $media->save();
        $comment->content = $filter_content;
        $comment->parent_id = $id;
        $comment->media_id = $media->id;
        $comment->save();
        if($comment){
            // 推送
            $_user = D('users')->find($mediacomment->uid);
            if ($_user && $_user->registration_id) {
                /*
                 Pusher::message($_user->registration_id, '其他用户回复了您发布的评论', ['type' => 2]);
                */
                $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $_user->registration_id]]);
                // 消息推送
                if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){
                    ////////////////////////////////////////////////////////////////////////////////////////////////
                    // 标题  --app 通过notify id 0处理业务 --透传
                    $data = [];
                    $push_channel_key = 'jpush';
                    if($getPushChannel['push_channel_id'] == 2){
                        $push_channel_key = 'hpush';
                    }else if($getPushChannel['push_channel_id'] == 3){
                        $push_channel_key = 'xmpush';
                    }

                    $data['channel_id'] = $getPushChannel['push_channel_id'];
                    $data['title'] = '回复评论'; // 登录标题
                    $data['content'] = '其他用户回复了您发布的评论';// 内容
                    $data['description'] = '其他用户回复了您发布的评论'; // 描述
                    $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                    $data['notify_id'] = 2;     // 通知id   --app 处理业务标识
                    $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                    $data['mobile_list'] = $getPushChannel['registration_id'];
                    $data['mobile_unique_code'] = IT('mobile_unique_code');
                    dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                    ////////////////////////////////////////////////////////////////////////////////////////////////
                }
            }
            if(strpos($user->avatar,$host) !== false){
                $avatar = getSignUrl($user->avatar);
            }else{
                $avatar =$user->avatar;
            }
            $data = [
                'uid' =>  $user->id,
                'username' => $user->name,
                'id'=> $comment->id,
                'avatar' => $avatar,
                'content' =>$comment->content,
                'replay_count' =>MediaComment::where('parent_id','=',$media->id)->count(),
                'created_at' =>time2date(),
            ];
        }
        return json_success('ok',$data, 10000);

    }

    /**
     * 用户主页
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function homePage(Request $request)
    {
        $uid = $request->input('uid');
        $myUser = User::getUserInfo($request->input('ticket'));
        if ($uid){      //如果是要查看其他用户主页
            $user = User::where('id',$uid)->first();
            if (!$user) {
                $_SERVER['message_code'] = 10049;
                throw new ApiException('您查看的用户未找到');
            }
        }else {
            $user =  $myUser ;
        }

        if (!$user){
            $_SERVER['message_code'] = 10005;
            throw new ApiException('该用户不存在');
        }

        // 是否加入黑名单
        $is_blacklist = 0;
        if(!empty($uid) && $myUser->id != $uid){
            $fail_friend_id = FailFriend::getRows([['uid', '=', $myUser->id], ['friend_uid','=', $uid], ['status', '=', '1']],['id']);
            $is_blacklist = (empty($fail_friend_id) ? 0 : 1);
        }

        // 获取用户视频总点赞
        $u_media_total_like = Media::where([['uid', '=', $user->id], ['status', '=', '1'], ['is_delete', '=', '0']])->sum('like');

        $user_basic = $user->only(['id','name','real_name','mobile','avatar','sex', 'birthday', 'signature']);
        $user_basic['uid'] = $user->id;
        $where = array(
            ['media_star.uid','=',$myUser->id],
            ['media_star.status','=',1],
            ['media.status','=',1],
            ['media.is_delete','=',0],
            ['media.is_forward','=',0]
        );

        $user_basic['is_blacklist'] = $is_blacklist;
        $user_basic['collection'] = D('media_star')->leftJoin('media','media_star.media_id','=','media.id')->where($where)->count();
        $user_basic['media_count'] = $user->_medias->count();
        $user_basic['fans_count'] = $user->fans;
        // $user_basic['follow_count'] = $user->_follow_friends()->where('status',1)->groupBy('uid')->get()->count();
        $user_basic['follow_count'] =  $user->attention;
        $user_basic['background'] = D('users_bg_picture')->where('id',$user->user_bg_picture)->first(['img']);
        $user_basic['role'] =  $user->role;//股东 0=普通用户 1=股东用户
        $user_basic['membership'] =  $user->membership;//推广会员 0=不是 1=是
        $user_basic['operations_manager'] =  0 ;//运营中西管理员 0=不是 1=是
        $where = [
            'friend_id'=>$uid ,
            'uid' =>$myUser->id,
            'status' => 1,
        ];
        $user_info = Friend::where($where)->first();
        if ($myUser && $user->id == $myUser->id ) {
            //自己不能关注自己
            $user_basic['is_author_star'] = -1;
            $user_basic['star_status'] = -1;
            $user_basic['friend_num'] = D('friend')->where([ ['uid', $myUser->id], ['status', 1] ])->count();  // 只有查看自己的主页才能看到亲友数量 //->orWhere([ ['friend_uid', $myUser->id], ['status', 1] ])
        }else if ($user_info){
            $user_basic['is_author_star'] = 1; //已关注
            $user_basic['star_status'] = 1;
        }else {
            $user_basic['is_author_star'] = 0; //未关注
            $user_basic['star_status'] = 0;
        }
        $user_basic['is_friend'] = 0;
        if ($myUser && $user->id != $myUser->id && $is_blacklist != 1) {
            $data = [$user->id, $myUser->id];
            sort($data);
            $user_basic['is_friend'] = D('friend')->where([ ['uid', $data[0]], ['friend_uid', $data[1]], ['status', 1] ])->first() ? 1 : 0;
            if ($user_basic['is_friend'] === 0) {
                $apply = D('friend_apply')->where([ ['uid', $user->id], ['apply_uid', $myUser->id] ])->first(['id','status']);
                if ($apply && ($apply->status == 0 || $apply->status == 3)) {
                    $user_basic['is_friend'] = 2;  // 已邀请
                }
            }
        }

        $has_activity = 0;
        $activity_info = ActivityConfig::select(['id'])->where([['status', '=', ActivityEnum::ACTIVITY_STATUS_VALID], ['end_time', '>', time()], ['activity_type', '=', ActivityEnum::ACTIVITY_TYPE_INVITE]])->orderBy('updated_at', 'desc')->first();
        $language_code = $request->input('language_code', 'zh-cn');
        /*if($activity_info && $language_code == 'zh-cn') {
            $has_activity = 1;
        }*/
        if($activity_info) {
            $has_activity = 1;
        }
        $user_basic['avatar'] = getSignUrl($user_basic['avatar']);
        $user_basic['praise'] = $u_media_total_like;
        $user_basic['has_activity'] = $has_activity; // 是否有活动

        return json_success('ok',$user_basic, 10000);
    }

    public function mediaList(Request $request)
    {
        $uid = $request->input('uid');
        $myUser = User::getUserInfo($request->input('ticket'));
        $page = intval($request->input('page')) ?: 1;
        $page -= 1;
        $pageSize = config('admin.pageSize');
        if ($uid) {      //如果是要查看其他用户主页
            $user = User::where('id', $uid)->first();
            if (!$user) {
                $_SERVER['message_code'] = 10049;
                throw new ApiException('您查看的用户未找到');
            }
        } else {
            $user = $myUser;
        }
        if (!$user){
            $_SERVER['message_code'] = 10005;
            throw new ApiException('该用户不存在');
        }

        // 收藏数 点赞数 分享数
        $fields = ['id', 'title','description', 'media', 'comments', 'star', 'like', 'share', 'uid', 'address','location','created_at', 'is_private', 'status', 'video_length', 'cover', 'is_screen_recording', 'is_participate_activity'];

        $where[] = ['uid','=', $user->id];
        $where[] = ['is_delete','=', 0];
        $where[] = ['is_forward','=', 0];
        $is_mine = $myUser->id == $user->id;
        // 查看他人主页
        if (!$is_mine) {
            $where[] = ['status','=', 1];
            $data = [$user->id, $myUser->id];
            sort($data);
            $friend = D('friend')->where([['uid', $data[0]], ['friend_uid', $data[1]], ['status', 1]])->first();
            // 亲友圈发布
            if ($friend)
                $where[] = ['is_private','!=', 1];
            else
                $where[] = ['is_private','=', 0];
        }else{
            $where[] = ['status','!=', 2];
        }

        $is_friend = 0;
        $is_attention = 0;
        // 登录状态，非自己
        if(!empty($myUser) && !empty($uid) && $myUser->uid != $uid){
            // 亲友
            $friend_rows_id = FriendModel::getRowsObj([['uid', '=', $myUser->id],['friend_uid', '=', $uid], ['status', '=', '1']], 'id');
            // 关注好友状态
            $friend_user_rows_id = FriendUser::getRowsObj([['uid', '=', $myUser->id],['friend_id', '=', $uid], ['status', '=', '1'], ['type', '=', 3]], 'id');
            if(!empty($friend_rows_id))
                $is_friend = 1;
            if(!empty($friend_user_rows_id))
                $is_attention = 1;
        }

        $media_list = Media::select($fields)->where($where)->orderBy('id', 'desc')->paginate($pageSize);
        $media_list_data = [];
        if(!empty($media_list)){
            $media_list_data = $media_list->items();
            foreach ($media_list_data as &$media)
            {
                $media->protected_avatar = !empty($media->_user->avatar) ? $media->_user->avatar : '';
                $media->protected_media = !empty($media->media) ? $media->media : '';

                $media->is_star = 0;
                $media->is_like = 0;
                if(!empty($myUser)){
                    $media->is_star = ($myUser && $myUser->_mediaStars()->where('media_id',$media->id)->first()) ? 1 : 0;
                    if ($myUser) {
                        $media_like = D('media_like')->where([ ['media_id', $media->id], ['uid', $myUser->id], ['is_delete', '=', '0'] ])->first();
                        $media->is_like = (!empty($media_like)) ? 1 : 0;
                    }
                }
                $media->is_my_homepage = $is_mine ? 1 : 0;    //自己的首页
                $media->media = getSignUrl($media->media);
                $media->cover = getSignUrl($media->cover);
                $media->username = !empty($media->_user->name) ? $media->_user->name : '';
                $media->avatar = !empty($media->_user->avatar) ? getSignUrl($media->_user->avatar) :'';
                $media->timestamp = $media->created_at->getTimestamp();
                //$media->viplevel = $media->_user->vip_level?:0;
                $media->is_friend = $is_friend;
                $media->is_attention = $is_attention;
                $media->sex = $user->sex;

                unset($media->_user,$media->isstockholder);
            }
        }


        return json_success('ok',$media_list_data, 10000);
    }

    /*
     * 个人动态
     * */
    public function dynamicList(Request $request)
    {
        $uid =  IT('uid');

        $page = intval($request->input('page'))?:1;
        $pageSize = 10;
        $filtration_video_chat = false;
        if ($uid){
            //如果是要查看其他用户主页
            $user = User::where('id',$uid)->first();
            if (!$user){
                $_SERVER['message_code'] = 10049;
                throw new ApiException('您查看的用户未找到');
            }

            // 处理用户查看自己的动态
            $current_user =  User::getUserInfo($request->input('ticket'));
            if($current_user->id != $uid) {
                $filtration_video_chat = true;
            }

        }else {
            $user =  User::getUserInfo($request->input('ticket'));
            $uid =  $user->id;
        }
        if (!$user){
            $_SERVER['message_code'] = 10005;
            throw new ApiException('该用户不存在');
        }

        $where_arr = [
            ['uid', '=', $uid],
            [ 'status','=',1]
        ];

        // 不能查看其他用户的视频聊天动态
        if($filtration_video_chat) {
            $where_arr[] = ['type', '!=', 4];
        }
        $list = UserDynamicList::where($where_arr)->with('option_user')->orderBy('id','desc')->paginate($pageSize);

        $dynamicLiset = $temp_arr = [];
        foreach ($list as $key=>$value){

            $temp_arr['id'] = $value->operation_id;
            $temp_arr['type'] = $value->type;
            $temp_arr['uid'] = $value->option_uid;
            $temp_arr['name'] = !isset($value->option_user) ? '' : $value->option_user->name;
            $temp_arr['avatar'] = empty($value->option_user->avatar) ? '' : getSignUrl($value->option_user->avatar);;
            $temp_arr['media_id'] = $value->media_id;
            $temp_arr['content'] = $value->option_content;
            $temp_arr['cover'] = getSignUrl($value->option_other);
            $temp_arr['duration'] = (time()-$value->create_time);
            $temp_arr['created_at'] = date("Y-m-d H:i:s", $value->create_time);
            $temp_arr['descript'] =   (!empty($uid) && $user->id != $uid) ? str_replace('你', '他', config('params.Dynamic_description.'.$value->type)) : config('params.Dynamic_description.'.$value->type);
            $dynamicLiset[] = $temp_arr;
        }
        $next_page = 1;
        if($page >= $list->lastPage())
            $next_page = 0;
        return json_success('ok',['next_page'=>$next_page, 'list'=>$dynamicLiset], 10000);
    }

    public function SharingVideo(Request $request)
    {
        $media_id = IT('id', true, '请选择预览的视频', 10050);
        $media = Media::find($media_id);
        if (!$media || !$media->media || !$media->cover || $media->status != '1' || $media->is_delete == '1') {
            $_SERVER['message_code'] = 10051;
            throw new ApiException('未找到相应内容');
        }
        $data['title'] = $media->title;
        $data['cover'] = getSignUrl($media['cover']);
        $data['media'] = getSignUrl($media['media']);;
        $data['video_length'] = $media->video_length;
        $data['avatar']= getSignUrl($media->_user->avatar) ? :'';
        $data['username']=$media->_user->name;
        $data['uid'] = $media->_user->id;
        $data['address'] = $media->location;
        return json_success('ok',$data, 10000);
    }

    public function RandomNumber()
    {
        $rand_data = Media::orderBy(\DB::raw('RAND()'))->first();
        $rand_data->media = getSignUrl($rand_data->media);
        $rand_data->cover = getSignUrl($rand_data->cover);
        return json_success('ok', ['id'=> $rand_data->id,'cover' => $rand_data->cover, 'media' => $rand_data->media, 'video_length' => $rand_data->video_length], 10000);
    }

    /**
     * 记录用户行为
     * @param Request $request
     * @return array
     */
    public function action(Request $request)
    {
        $uid = D('user_tickets')->where([['ticket', '=', $request->input('ticket')], ['status', '=', 1]])->value('uid');
        $media_id = (int) IT('media_id', true, '请选择观看视频', 10041);
        $action = (int) IT('action', true, '请选择动作', 10052);
        $duration = (int) $request->input('duration');
        $mobile_unique_code = IT('mobile_unique_code');

        if (!in_array($action, [1, 2]))
            return json_error('参数有误',[], 10032);
        if ($action === 2 && !$duration)
            return json_error('请上传观看视频时长', [], 10053);
        $media = D('media')->find($media_id);
        if (!$media || $media->status == 0 || $media->is_delete == 1)
            return json_error('视频不存在', [], 10054);

        if ($action == 1) {
            $duration = 0;
            D('media')->where('id', $media_id)->increment('share');  // 增加分享次数
        }else if($action == 2){
            D('media')->where('id', $media_id)->increment('pv');  // 增加浏览次数
        }

        // 获取设备信息
        $mobile_unique_code = MobileMark::getRowsArray([['mobile_unique_code', '=', $mobile_unique_code]]);

        $mobileMarkId = empty($mobile_unique_code) ? '0' : $mobile_unique_code['id'];
        $province = empty($mobile_unique_code['province']) ? '0' : $mobile_unique_code['province'];
        $city = empty($mobile_unique_code['city']) ? '0' : $mobile_unique_code['city'];

        // 写入行为记录
        // Behavior::write($uid, $media_id, $action, $duration, $mobileMarkId, $province, $city);

        // 队列  --写入行为记录
        $data['uid'] = empty($uid) ? 0 : $uid;
        $data['media_id'] = $media_id;
        $data['action'] = $action;
        $data['duration'] = $duration;
        $data['mobileMarkId'] = $mobileMarkId;
        $data['province'] = $province;
        $data['city'] = $city;
        $data['ticket'] = $request->input('ticket');
        Redis::rPush('algorithm_log', json_encode(['type'=>'recommend', 'create_time'=>time(), 'data'=>$data]));

        // 可删除
        // dispatch((new LogQueue(['type'=>'recommend', 'data'=>$data]))->onQueue('log_queue'));

        return json_success('ok', [], 10000);
    }

    /*
     * 绑定定位
     * */
    public function pushPlace(Request $request)
    {
        $mobile_unique_code = IT('mobile_unique_code', true, '参数有误', 10032);
        $province = IT('province', true, '省份参数有误',10055);
        $city =  IT('city', true, '城市参数有误',10056);
        $address = IT('address', true, '地址参数有误',10057);

        $result = MobileMark::saveMark($request);
        if($request == false)
            return json_error('推送定位失败', [], 10058);

        return json_success('ok',[],10000);
    }

    /*
     * 文件上传
     * */
    public function fileUpload(Request $request)
    {
        $type = IT('type', true, '文件类型必填', 10059);
        $img_url = IT('img_url', true, '图片文件必传', 10060);

        if(!in_array($type, config('params.upload_file_type')))
            return json_error('未知上传类型', [], 10061);

        $result = UploadService::$type($request);
        if(!isset($result['status']) || $result['status'] == 'error'){
            $msg = empty($result['message']) ? '上传失败' : $result['message'];
            $message_code = empty($result['message_code']) ? 10001 : $result['message_code'];
            return json_error($msg, [], $message_code);
        }
        if(isset($result['status']) && $result['status'] == 'success' && $type == 'member_avatar' )
            return json_success('ok', !empty($result['data']) ? $result['data']: null, 10000);

        return json_success('ok', [], 10000);
    }

    /*
     * 获取oss 可访问资源
     * */
    public function index_oss_resource(Request $request)
    {
        $resourceUrl = IT('url', true, '资源url参数有误', 10062);
        $resourceUrl = getSignUrl($resourceUrl);
        return json_success('ok', $resourceUrl, 10000);
    }

    /*
     * 下载证书
     * */
    public function index_download(Request $request)
    {
        $type = IT('type', true, '请选择要下载的证书类型', 10063);
        $user = User::getUserInfo($request->input('ticket'));

        if(!in_array($type, config('params.download_type')))
            return json_error('请选择要下载的证书类型', 10064);
        $shareholder = UserService::getShareholder($user->mobile);
        if(empty($shareholder) || $shareholder->status == 1 )
            return json_error('股东用户不存在', [], 10065);

        // 协议
        $data = [];
        if($type == 'shareholder_agreement'){
            if(empty($shareholder->shareholder_agree_img))
                return json_error('协议证书不存在', [], 10066);
            $shareholder_agree_img_arr = explode(',', $shareholder->shareholder_agree_img);
            sort($shareholder_agree_img_arr);
            foreach ($shareholder_agree_img_arr as $value)
                $data[] = getSignUrl($value);
            $shareholder->shareholder_agree_img = empty($temp_arr) ? null : $temp_arr;

        }
        // 证书
        else if($type == 'shareholder_certificate'){
            if(empty($shareholder->shareholder_certificate_img))
                return json_error('股东证书不存在',[],10067);
            $shareholder_certificate_img_arr = explode(',', $shareholder->shareholder_certificate_img);
            sort($shareholder_certificate_img_arr);
            foreach ($shareholder_certificate_img_arr as $value)
                $data[] = getSignUrl($value);
        }

        return json_success('ok', empty($data) ? null : $data, 10000);
    }

    /*
     * 视频详情含评论
     * */
    public function media_mediaDetail(Request $request)
    {
        $uid = $this->uid;
        $media_id = IT('media_id', true, '未知视频资讯',10068);

        // 获取视频详情
        $data = MediaService::getDataOfMediaDetail($request);

        return json_success('ok', $data, 10000);
    }

    /**
     * @desc 分享二维码
     * @return array
     */
    public function get_shareQRCode()
    {
        $ticket = IT('ticket');
        $qr_code = null;
        $avatar = '';
        $Invitation_code = 0;
        if($ticket) {
            $uid = D('user_tickets')->where([['ticket', '=', $ticket], ['status', '=', 1]])->value('uid');
            if(empty($uid))
                EE('用户未登录', 1000, 10004);

            $user_info = D('users')->where(['users.id' => $uid])->join('user_invitation_code','user_invitation_code.uid', '=', 'users.id' )->first(['users.role', 'users.membership', 'users.avatar','user_invitation_code.invitation_code']);
           /* if($user_info && ($user_info->role == 1 || $user_info->membership == 1)) {*/
                $qr_code = config('app.url').'/api/Sharing_links?share_type=main&channel=wx&uid='.$uid;
                $avatar = $user_info->avatar ? getSignUrl($user_info->avatar) : '';
                $Invitation_code = empty($user_info->invitation_code) ? '' : $user_info->invitation_code ;
            /*}*/

        }
        return json_success('ok', ['qr_code' => $qr_code, 'avatar' => $avatar,'Invitation_code' => $Invitation_code,], 10000);
    }

    /*`
     * 活动排行榜
     * */
    public function index_activity_ranking(Request $request)
    {
        $data = [];
        $type = IT('type', true, '参数有误', 10032);

        $activity_config = ActivityConfig::where([['activity_type', '=', 2], ['status', '=', 1]])->orderBy('id', 'desc')->first();
        if(empty($activity_config))
            return json_error('活动已结束', null, 10262);
        if($activity_config->status != 1)
            return json_error('活动已结束', null, 10262);
        if($activity_config->start_time > time())
            return json_error('活动未开始', null, 10263);
        if($activity_config->last_show_time < time())
            return json_error('活动已结束', null, 10262);

        // 初始化
        $w = date("W", time());
        $data['week_format'][] = ['date_format'=>(int)$w, 'title'=>'本周榜单'];
        $data['month_format'][] = ['date_format'=>forward_month(0), 'title'=>'本月榜单'];

        $weekday_1 = weekday(date("Y", time()), (date("W", time())-1));
        $weekday_2 = weekday(date("Y", time()), (date("W", time())-2));
        $weekday_3 = weekday(date("Y", time()), (date("W", time())-3));
        // 校验前一周时间
        if($activity_config->start_time <= strtotime(date("Y-m-d ", $weekday_1['end'])." 23:59:59"))
            $data['week_format'][] = ['date_format'=>(int)date("W", $weekday_1['start']), 'title'=>date("d", $weekday_1['start']).'日-'.date("d", $weekday_1['end']).'日榜单'];
        // 校验前两周时间
        if($activity_config->start_time <= strtotime(date("Y-m-d ", $weekday_2['end'])." 23:59:59"))
            $data['week_format'][] = ['date_format'=>(int)date("W", $weekday_2['start']), 'title'=>date("d", $weekday_2['start']).'日-'.date("d", $weekday_2['end']).'日榜单'];
        // 校验前三周时间
        if($activity_config->start_time <= strtotime(date("Y-m-d ", $weekday_3['end'])." 23:59:59"))
            $data['week_format'][] = ['date_format'=>(int)date("W", $weekday_3['start']), 'title'=>date("d", $weekday_3['start']).'日-'.date("d", $weekday_3['end']).'日榜单'];

        if(date("Ym", $activity_config->start_time) <= forward_month(1))
            $data['month_format'][] = ['date_format'=>forward_month(1), 'title'=>date("m", strtotime(forward_month(1)."01 00:00:00")).'月榜单'];
        if(date("Ym", $activity_config->start_time) <= forward_month(2))
            $data['month_format'][] = ['date_format'=>forward_month(2), 'title'=>date("m", strtotime(forward_month(2)."01 00:00:00")).'月榜单'];
        if(date("Ym", $activity_config->start_time) <= forward_month(3))
            $data['month_format'][] = ['date_format'=>forward_month(3), 'title'=>date("m", strtotime(forward_month(3)."01 00:00:00")).'月榜单'];

        $data['type'] = (int)$type;
        $data['activity_title'] = null;
        $data['activity_content'] = null;
        $data['list'] = null;
        if(!empty($activity_config) && (time() >=  $activity_config->start_time) && (time() <= $activity_config->last_show_time)){
            $data['activity_content'] = $activity_config->content;
            $data['activity_title'] = $activity_config->title;

            $activity_service = new ActivityService();
            $list = $activity_service->get_activity_ranking($request, $activity_config->id);
            $data['list'] = empty($list) ? null : $list;
        }
        return json_success('ok', $data, 10000);
    }
}